package com.fh.web.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.fh.bo.PageFilterBo;
import com.fh.bo.PurviewBo;
import com.fh.dao.PubSystemMapper;
import com.fh.dao.PurPurviewMapper;
import com.fh.dao.SysUserMapper;
import com.fh.dto.PubSystem;
import com.fh.dto.PurPurview;
import com.fh.dto.PurUser2Role;
import com.fh.dto.SysUser;
import com.fh.web.constants.UserConstants;
import com.fh.web.service.UserMangerService;
import com.fh.web.vo.SysUserVo;
import com.fh.dao.PurUser2RoleMapper;
import com.fh.web.constants.FhManagerConstant;
import com.fh.web.constants.GlobalConstants;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;
import tk.mybatis.mapper.util.StringUtil;

@Service("userMangerService")
public class UserMangerServiceImpl implements UserMangerService {
	@Resource
	private PurPurviewMapper purviewDao;

	@Resource
	private SysUserMapper sysUserDao;
	
	@Resource
	private PurUser2RoleMapper userRoleDtoMapper;

	@Resource
	private PubSystemMapper pubSystemMapper;
	/**
	 * 用户在权限点所拥有的操作
	 */
	@Override
	public Map<String, Object> userCanOperation(SysUserVo user, String pId) throws Exception {
		Map<String, Object> resMap = new HashMap<String, Object>();
		List<PurPurview> userPurList = null;
		if (user.getUserCode().equals(UserConstants.SUPERADMIN)) {
			// 系统默认超级管理员，默认拥有权限点下的所有操作权限点
			userPurList = purviewDao.getOperPurByPurId(pId);
		} else {
			// 其他用户要根据角色来确定用户拥有的权限
			userPurList = purViewOperation(user.getUserId().toString(), pId);
		}
		for (int i = 0; i < userPurList.size(); i++) {
			resMap.put(userPurList.get(i).getPurCode(), true);
		}
		return resMap;
	}

	@Override
	public Map<String, Object> selectAllUser(PageFilterBo ph, String sysCode, String userName) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<SysUser> userList = new ArrayList<SysUser>();
		PageHelper.startPage(ph.getPage(), ph.getRows());
		PageHelper.orderBy("USER_ID desc");
		Example example = new Example(SysUser.class);
		Criteria criteria = example.createCriteria();
		if(!StringUtil.isEmpty(userName)){
			criteria.andLike("userCode", "%"+userName+"%");
			
		}
       if(!StringUtil.isEmpty(sysCode) && !sysCode.equals("0")){
    	   criteria.andEqualTo("sysCode", sysCode);
		}
        criteria.andNotLike("userCode", GlobalConstants.SYS_ADMIN);
		userList = sysUserDao.selectByExample(example);
		map.put("list", userList);
		PageInfo<SysUser> pageSysUserList = new PageInfo<SysUser>(userList);
		map.put("pageTotal", pageSysUserList.getTotal());
		return map;
	}

	@Override
	public SysUser editUser(Long id) throws Exception {
		SysUser sysUser1 = (SysUser) sysUserDao.selectByPrimaryKey(id);
		SysUserVo sysUser = SysUserVo.getSysUserVo(sysUser1);
		/** 更具地区编号查询父节点 */
		/*PubOrg orgDto = pubOrgDao.selectByPrimaryKey(sysUser.getOrgId());
		sysUser.setOrgName(orgDto.getOrgName());
		*//** 更新用户的角色关系 */
		Example example = new Example(PurUser2Role.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", id);
		List<PurUser2Role> userRoleList = userRoleDtoMapper.selectByExample(example);
		String idsStr = "";
		for (PurUser2Role userRoleDto : userRoleList) {
			idsStr += userRoleDto.getRoId() + ",";
		}
		if (idsStr != null && !"".equals(idsStr)) {
			idsStr = idsStr.substring(0, idsStr.length() - 1);
		}
		sysUser.setRoleIds(idsStr);
		return sysUser;
	}

	@Override
	public int updateUserById(SysUserVo userBean, Integer createUserId) throws Exception {
		int succ = FhManagerConstant.RST_FAIL;
		if (null != userBean) {
			Long userId = userBean.getUserId();
			/** 删除关系表数据 */
			Example example = new Example(PurUser2Role.class);
			Criteria criteria = example.createCriteria();
			criteria.andEqualTo("userId", userId);
			userRoleDtoMapper.deleteByExample(example);
			/** 重新添加数据 */
			List<PurUser2Role> userRoleDtoList = new ArrayList<PurUser2Role>();
			String[] ids = userBean.getRoleIds().split(",");
			for (String id : ids) {
				PurUser2Role userRoleDto = new PurUser2Role();
				userRoleDto.setRoId(Integer.valueOf(id));
				userRoleDto.setUserId(userId.intValue());
				userRoleDto.setCreateUserId(createUserId);
				userRoleDtoList.add(userRoleDto);
			}
			userRoleDtoMapper.insertIntoUserRole(userRoleDtoList);
			// 更新用户备注说明
			userBean.setUpdateTime(new Date());
			sysUserDao.updateByPrimaryKeySelective(userBean);
			succ = FhManagerConstant.RST_SUCCESS;
		}
		return succ;
	}

	public List<PurPurview> purViewOperation(String uId, String pId) throws Exception {
		return sysUserDao.getPurViewOperation(uId, pId);
	}
	/**
	 * 查询所有平台信息
	 */
	@Override
	public List<PubSystem> getSysCode() throws Exception {
		return pubSystemMapper.selectAll();
	}

	@Override
	public int deleteUserById(Long id) throws Exception {
		return sysUserDao.deleteUserById(id);
	}
	
	@Override
	public int updateUserById(Long id) throws Exception {
		return sysUserDao.updateUserById(id);
	}
}
